package org.vison.wonfu.framework.soa.discovery.LoadBalanceImpl;

import org.vison.wonfu.framework.soa.annotation.LoadBalance;
import org.vison.wonfu.framework.soa.discovery.LoadBalanceAlgorithm;
import org.vison.wonfu.framework.soa.discovery.ServiceInstance;

import java.util.List;
import java.util.Random;

/**
 * 随机负载均衡算法
 * 随机选择一个可用的服务实例，适用于服务实例性能相近的场景
 */
public class RandomAlgorithm implements LoadBalanceAlgorithm {
    private final Random random = new Random();
    private  List<ServiceInstance> serviceInstances;

    public void setServiceInstances(List<ServiceInstance> serviceInstances) {
        this.serviceInstances = serviceInstances;
    }

    @Override
    public ServiceInstance select() {
        if (serviceInstances == null || serviceInstances.isEmpty()) {
            return null;
        }

        // 随机选择一个可用实例
        int index = random.nextInt(serviceInstances.size());
        return serviceInstances.get(index);
    }

    @Override
    public LoadBalance getType() {
        return LoadBalance.RANDOM;
    }
}
